﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JigLibX.Collision;
using JigLibX.Geometry;
using JigLibX.Math;
using JigLibX.Utils;
using JigLibX.Physics;
using Microsoft.Xna.Framework;

namespace DARE
{
    public class CPhysicTerrain : APhysicObject
    {

        #region fields

        private CTerrainInfo m_terrainInfo;
        private Vector3 m_position;

        #endregion

        #region properties

        public CTerrainInfo TerrainInfo
        {
            get { return m_terrainInfo; }
        }

        #endregion

        #region ctor

        public CPhysicTerrain(CTerrainInfo terrainInfo)
        {
            Initialize(terrainInfo, Vector3.Zero);
        }

        public CPhysicTerrain(CTerrainInfo terrainInfo, Vector3 position)
        {
            Initialize(terrainInfo, position);
        }

        private void Initialize(CTerrainInfo terrainInfo, Vector3 position)
        {
            if (terrainInfo == null)
                throw new Exception("CPhysicTerrain: terrainInfo cannot be null !");
            m_terrainInfo = terrainInfo;
            m_position = position;
            m_body = new Body();
            m_collisionSkin = new CollisionSkin(null);
            m_body.CollisionSkin = m_collisionSkin;

            Array2D field = new Array2D(m_terrainInfo.Heightmap.Width, m_terrainInfo.Heightmap.Height);

            for (int z = 0; z < m_terrainInfo.Heightmap.Height; ++z)
                for (int x = 0; x < m_terrainInfo.Heightmap.Width; ++x)
                    field.SetAt(x, z, m_terrainInfo.Infos[x, z].position.Y + m_position.Y);

            m_collisionSkin.AddPrimitive(new Heightmap(field, m_position.X, m_position.Z, m_terrainInfo.Scale, m_terrainInfo.Scale),
                new MaterialProperties(0.7f, 0.7f, 0.6f));
            m_body.EnableBody();
            m_body.Immovable = true;
        }

        #endregion

        #region methods

        public override APhysicObject Clone()
        {
            CPhysicTerrain clone = new CPhysicTerrain(m_terrainInfo, m_position);

            base.CopyPropertiesTo(clone);
            return clone;
        }

        #endregion

    }
}
